package com.example.service.impl;

import com.example.mapper.ContentMapper;
import com.example.mapper.ContentcategoryMapper;
import com.example.pojo.Content;
import com.example.pojo.ContentCategory;
import com.example.pojo.ContentExample;
import com.example.service.ContentService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class ContentServiceImpl implements ContentService {
    @Autowired
    private ContentMapper contentMapper;

    @Autowired
    private ContentcategoryMapper contentcategoryMapper;

    @Autowired
    private RedisTemplate redisTemplate;

    @Override
    public List<Content> queryAll() {
        return contentMapper.selectByExample(null);
    }

    @Override
    public List<ContentCategory> queryAllContentCategory() {
        return contentcategoryMapper.selectByExample(null);
    }

    @Override
    public int saveOrUpdate(Content content) {
        int rs = 0;
        if (content.getId() == null){
            rs = contentMapper.insert(content);
        }else {
            //如果新旧分类Id不一致，删除属于旧分类的redis缓存
            Content oldContent = contentMapper.selectByPrimaryKey(content.getId());
            if (content.getCategoryId() != oldContent.getCategoryId()){
                redisTemplate.opsForHash().delete("content",oldContent.getCategoryId());
            }
            rs = contentMapper.updateByPrimaryKey(content);
        }
        //新增或修改成功，删除redis缓存
        if (rs >= 1){
            redisTemplate.opsForHash().delete("content",content.getCategoryId());
        }

        return rs;
    }

    @Override
    public int deleteById(Long id) {
        Content content = contentMapper.selectByPrimaryKey(id);
        redisTemplate.opsForHash().delete("content",content.getCategoryId());
        return contentMapper.deleteByPrimaryKey(id);
    }

    @Override
    public List<Content> queryContentByCategoryId(Long categoryId) {
        List<Content> contents = (List<Content>) redisTemplate.opsForHash().get("content",categoryId);

        if (contents == null || contents.isEmpty()){
            ContentExample example = new ContentExample();
            ContentExample.Criteria criteria = example.createCriteria();

            criteria.andStatusEqualTo("1");
            criteria.andCategoryIdEqualTo(categoryId);
            example.setOrderByClause("sort_order");

            contents = contentMapper.selectByExample(example);

            redisTemplate.opsForHash().put("content",categoryId,contents);
        }
        return contents;
    }
}
